import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCDemo4 {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("665181");

        //建立连接
        Connection connection = dataSource.getConnection();

        //3.  构造 SQL
        String sql = "select * from test";
        PreparedStatement statement = connection.prepareStatement(sql);

        //执行sql
        ResultSet resultSet = statement.executeQuery();

        //遍历结果集合
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = " + id +", name = " + name);
        }
        resultSet.close();
        statement.close();
        connection.close();
    }
}
